package com.zzy.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zzy.common.core.redis.RedisCache;
import com.zzy.common.utils.StringUtils;
import com.zzy.common.utils.guanmai.GuanmaiCommon;
import com.zzy.system.domain.*;
import com.zzy.system.domain.vo.PurchaseOrderVO;
import com.zzy.system.mapper.*;
import com.zzy.system.service.IPurchaseOrderDetailService;
import com.zzy.system.service.IPurchaseOrderDetailitemService;
import com.zzy.system.service.IPurchaseOrderService;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.*;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class PurchaseOrderServiceImpl extends ServiceImpl<PurchaseOrderMapper, PurchaseOrder> implements IPurchaseOrderService {

    private static final Logger log = LoggerFactory.getLogger(PurchaseOrderServiceImpl.class);



    @Autowired
    private IPurchaseOrderDetailService iPurchaseOrderDetailService;

    @Autowired
    private IPurchaseOrderDetailitemService iPurchaseOrderDetailitemService;


    // 陕生鲜客户编码
    @Value("${api.custCode}")
    private String custCode;
    //陕生鲜加密key
    @Value("${api.key}")
    private String key;
    //陕生鲜接口地址
    @Value("${api.shanshengxianUrl}")
    private String shanshengxianUrl;
    @Autowired
    private GuanmaiSupplierMapper guanmaiSupplierMapper;
    @Autowired
    private GuanmaiSpuMapper guanmaiSpuMapper;
    @Autowired
    private GuanmaiCustomerMapper guanmaiCustomerMapper;


    //请求观麦 获取订单集合
    public String getGuanmaiPurchaseOrderList(Integer status,String startDate,String endDate,Integer offset,Integer limit){
        List<PurchaseOrder> allPurchaseInfoList = new ArrayList<>();
        while (true) {
            Map<String, Object> paramMap = new HashMap<>();
            // 设置开始日期参数
            paramMap.put("start_date", startDate);
            // 设置截止日期参数
            paramMap.put("end_date", endDate);
            // 设置采购单据状态参数（这里示例设置为已提交状态，值为2，不传会查出全部，可按需不传该参数）
            paramMap.put("status", status);
            // 设置分页offset参数（默认值为0，可按需不传该参数或者修改值）
            paramMap.put("offset", offset);
            // 设置分页limit参数（默认值为100，取值范围<=100，可按需不传该参数或者修改值）
            paramMap.put("limit", limit);

            //请求观麦 获取订单列表
            String reponse = GuanmaiCommon.sendRequestGet(paramMap,"/v1/api/purchase/purchase_sheet/list/1.0" );
            JSONObject reponseJson = JSONObject.parseObject(reponse);
            if (reponseJson.get("code").toString().equals("0")) {
                JSONArray jsonArray = reponseJson.getJSONArray("data");
                if (jsonArray!= null) {
                    // 将当前页的数据解析并添加到总的结果列表中
                    List<PurchaseOrder> purchaseInfoList = jsonArray.toJavaList(PurchaseOrder.class);
                    allPurchaseInfoList.addAll(purchaseInfoList);
                    // 如果返回的数据条数等于每页显示的数量，说明可能还有更多数据，继续查询下一页
                    if (jsonArray.size() == limit) {
                        offset += limit; // 页码增加，指向下一页
                        continue;
                    } else {
                        // 如果返回的数据条数小于每页显示的数量，说明已经查询完所有数据，结束循环
                        break;
                    }
                }
            } else {
                // 如果接口返回的code不是0，表示请求出现问题，这里可以根据实际情况进行错误处理
                System.out.println("请求出现问题，错误信息：" + reponseJson.get("msg"));
                break;
            }

        }
        int batchSize = 100;
        for (int i = 0; i < allPurchaseInfoList.size(); i += batchSize) {
            int endIndex = Math.min(i + batchSize, allPurchaseInfoList.size());
            List<PurchaseOrder> batchList = allPurchaseInfoList.subList(i, endIndex);
            // 这里可以将batchList用于实际的saveBatch操作或者其他处理
            System.out.println("当前批次数据量: " + batchList.size());

            batchInsert(batchList,batchSize);

        }
        System.out.println(allPurchaseInfoList);
        return "";
    }

    @Override
    @Transactional
    public String getGuammaiPurchaseOrderDetails() throws JsonProcessingException {
        QueryWrapper<PurchaseOrder> queryWrapper = new QueryWrapper<>();

        // 使用notExists方法结合子查询构建条件，获取不在purchase_order_detail表中的purchase_sheet_id集合
        queryWrapper.select("purchase_sheet_id")
                .notExists("SELECT 1 FROM purchase_order_detail WHERE purchase_order_detail.purchase_sheet_id = purchase_order.purchase_sheet_id");

        List<String> purchaseSheetIdList= baseMapper.selectObjs(queryWrapper).stream()
                .map(obj -> (String) obj)
                .collect(Collectors.toList());
        for(String purchaseSheetId:purchaseSheetIdList){
            senGauanMaiOrderDetail(purchaseSheetId);
        }
        return "";
    }
    public void senGauanMaiOrderDetail(String purchaseSheetId) throws JsonProcessingException {
        Map<String, Object> paramMap=new HashMap<>();
        // 设置开始日期参数
        paramMap.put("purchase_sheet_id", purchaseSheetId);
        //请求观麦 获取订单列表
        String reponse = GuanmaiCommon.sendRequestGet(paramMap,"/v1/api/purchase/purchase_sheet/get/1.0" );
        JSONObject reponseJson = JSONObject.parseObject(reponse);
        if (reponseJson.get("code").toString().equals("0")) {
            JSONObject jsonObject = reponseJson.getJSONObject("data");
            PurchaseOrderDetail purchaseOrderDetail = JSON.parseObject(jsonObject.toString(), PurchaseOrderDetail.class);
            iPurchaseOrderDetailService.saveOrderDetail(purchaseOrderDetail);
            // 使用forEach方法遍历Details集合并设置purchaseSheetId属性
            purchaseOrderDetail.getDetails().forEach(detail -> detail.setPurchaseSheetId(purchaseSheetId));

            iPurchaseOrderDetailitemService.saveBatchList(purchaseOrderDetail.getDetails());
            System.out.println(purchaseOrderDetail);

        }
    }

    public void batchInsert(List<PurchaseOrder> allPurchaseInfoList, int batchSize) {
        // 提前查询数据库中已存在的purchase_order_sheetid集合
        List<String> existingSheetIds = getExistingPurchaseOrderSheetIds(allPurchaseInfoList);
        // 过滤掉已存在的purchase_order_sheetid对应的记录
        List<PurchaseOrder> filteredList = filterExistingRecords(allPurchaseInfoList, existingSheetIds);
        // 按批次插入过滤后的数据
        for (int i = 0; i < filteredList.size(); i += batchSize) {
            int endIndex = Math.min(i + batchSize, filteredList.size());
            List<PurchaseOrder> batchList = filteredList.subList(i, endIndex);
            System.out.println("当前批次数据量: " + batchList.size());
            this.saveBatch(batchList);

        }
    }
    private List<String> getExistingPurchaseOrderSheetIds(List<PurchaseOrder> purchaseOrders) {
        if (purchaseOrders == null || purchaseOrders.isEmpty()) {
            return new ArrayList<>();
        }

        List<String> sheetIdList = new ArrayList<>();
        for (PurchaseOrder order : purchaseOrders) {
            sheetIdList.add(order.getPurchaseSheetId());
        }

        QueryWrapper<PurchaseOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("purchase_sheet_id").in("purchase_sheet_id", sheetIdList);

        return this.getBaseMapper().selectObjs(queryWrapper).stream()
                .map(obj -> (String) obj).collect(Collectors.toList());
    }

    private List<PurchaseOrder> filterExistingRecords(List<PurchaseOrder> purchaseOrders, List<String> existingSheetIds) {
        List<PurchaseOrder> filteredList = new ArrayList<>();
        for (PurchaseOrder order : purchaseOrders) {
            if (!existingSheetIds.contains(order.getPurchaseSheetId())) {
                filteredList.add(order);
            }
        }
        return filteredList;
    }




}